/*
 * gcc -Wall -g example.c -o example `pkg-config clutter-0.8 clutter-gtk-0.8 --cflags  --libs`
 *
 */

#include <clutter/clutter.h>
#include <stdlib.h>

ClutterActor *rect = NULL;

gint rotation_angle = 0;
gint color_change_count = 0;
gint rotation_direction = 1;

void
on_timeline_new_frame (ClutterTimeline *timeline, gint frame_num, gpointer data)
{
		rotation_angle += rotation_direction;
		if (rotation_angle >= 360)
				rotation_angle = 0;
		
		/* Rotation the rectangle across its X axis */
		clutter_actor_set_rotation (rect, CLUTTER_X_AXIS, rotation_angle, 0, 0, 0);
		
		/* Make it flash */
		++color_change_count;
		if (color_change_count > 100)
				color_change_count = 0;
		
		if (color_change_count == 0)
		{
				ClutterColor rect_color = { 0xff, 0xff, 0xff, 0x99 };
				clutter_rectangle_set_color (CLUTTER_RECTANGLE (rect), &rect_color);
		}
		else if (color_change_count >= 50)
		{
				ClutterColor rect_color = { 0x10, 0x40, 0x90, 0xff };
				clutter_rectangle_set_color (CLUTTER_RECTANGLE (rect), &rect_color);
		}
}

static void
on_stage_press (ClutterStage *stage, ClutterEvent *event, gpointer user_data)
{ 
		rotation_direction *= -1;
		return TRUE;
}

/* Main */
int main(int argc, char *argv[])
{
		ClutterColor stage_color = { 0x00, 0x00, 0x00, 0xff };
		ClutterColor rect_color = { 0xff, 0xff, 0xff, 0x99 };
		
		clutter_init (&argc, &argv); 
		
		/* Get stage, set color and size */
		ClutterActor *stage = clutter_stage_get_default ();
		clutter_actor_set_size (stage, 200, 200);
		clutter_stage_set_color (CLUTTER_STAGE (stage), &stage_color);
		
		/* Add rectangle */
		rect = clutter_rectangle_new_with_color (&rect_color);
		clutter_actor_set_size (rect, 70, 70);
		clutter_actor_set_position (rect, 70, 75);
		
		clutter_container_add_actor (CLUTTER_CONTAINER (stage), rect);
		clutter_actor_show (rect);
		
		/* Show the stage*/
		clutter_actor_show (stage);
		
		/* Timeline Stuff */
		ClutterTimeline *timeline = clutter_timeline_new (10 /* frame */, 120 /* fps */);
		g_signal_connect (timeline, "new-frame",
											G_CALLBACK (on_timeline_new_frame), NULL);
		clutter_timeline_set_loop (timeline, TRUE);
		clutter_timeline_start (timeline);
		
		/* Click Callback */
		g_signal_connect (stage, "button-press-event",
											G_CALLBACK (on_stage_press), NULL);
		
		/* Main loop */
		clutter_main ();
		
		g_object_unref (timeline);
		
		return EXIT_SUCCESS;
}
